package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.*;
import com.zrrd.reggie.mapper.SetmealDishMapper;
import com.zrrd.reggie.mapper.SetmealMapper;
import com.zrrd.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    @Transactional//事务控制
    public void saveSetmeal(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishList = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish:setmealDishList){
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishMapper.insert(setmealDish);
        }
    }

    @Override
    @Transactional//事务控制
    public void updateSetmeal(SetmealDto setmealDto) {
        //更新自己的表直接调用
        this.updateById(setmealDto);
        //创建条件构造器
        QueryWrapper<SetmealDish> wrapper = new QueryWrapper<>();

        wrapper.eq("setmeal_id",setmealDto.getId());
        ////找到对应的外键删掉

        setmealDishMapper.delete(wrapper);//逻辑删除取消
        //重新写入保存
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for(SetmealDish setmealDish:setmealDishes){
            setmealDish.setSetmealId(setmealDto.getId());
            setmealDishMapper.insert(setmealDish);
        }
    }

    @Override
    public void deleteSetmeal(Long[] ids) {
        List<Long> list = Arrays.asList(ids);
        this.removeByIds(list);
        for (Long id:list){
            QueryWrapper<SetmealDish> wrapper =new QueryWrapper();
            wrapper.eq("setmeal_id",id);
            setmealDishMapper.delete(wrapper);
        }
    }
}
